/**
 * This file is part of the Kompics P2P Framework.
 *
 * Copyright (C) 2009 Swedish Institute of Computer Science (SICS)
 * Copyright (C) 2009 Royal Institute of Technology (KTH)
 *
 * Kompics is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package se.sics.drsm.components;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.sics.drsm.inits.GroupCommunicationInit;
import se.sics.drsm.messages.UpdateConfiguration;
import se.sics.drsm.model.DRSMAddress;
import se.sics.drsm.ports.statemachine.StateMachinePort;
import se.sics.drsm.ports.statemachine.events.ReConfigurationRequest;
import se.sics.kompics.ComponentDefinition;
import se.sics.kompics.Handler;
import se.sics.kompics.Positive;
import se.sics.kompics.network.Network;
import se.sics.kompics.timer.Timer;

/**
 * The <code>GroupCommunication</code> class.
 *
 * @author Shadid Chowdhury <msrch@kth.se>
 */
public class GroupCommunication extends ComponentDefinition {

    Positive<StateMachinePort> stateMachinePort = positive(StateMachinePort.class);
    Positive<Network> network = positive(Network.class);
    Positive<Timer> timer = positive(Timer.class);

    private Logger logger = LoggerFactory.getLogger(getClass().getName());


    public GroupCommunication() {
        subscribe(handleInit, control);
        subscribe(handleReConfigurationRequest, stateMachinePort);

    }

    Handler<GroupCommunicationInit> handleInit = new Handler<GroupCommunicationInit>() {
        public void handle(GroupCommunicationInit init) {
            logger.debug("GroupCommunicationInit");
//            logger = LoggerFactory.getLogger(getClass().getName() + "@"
//                    + self.getKey().getId());
        }
    };

    private Handler<ReConfigurationRequest> handleReConfigurationRequest = new Handler<ReConfigurationRequest>() {
        public void handle(ReConfigurationRequest event) {
            logger.debug("handleReConfigurationRequest");
            // TODO: new peer should not recieve this or decide?
            for (DRSMAddress destination : event.getMachineConfiguration().getPeerList())
                trigger(new UpdateConfiguration(event.getSender(), destination, event.getMachineConfiguration()), network);

        }
    };

}
